package com.lianqi.emcpframework.core.generator;

import com.lianqi.emcpframework.utils.RandomUtil;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program emcp-framework
 * @ClassName IDGenerator
 * @description: id生成器
 * @author: sky
 * @create: 2018/11/13 09:20
 */
@FunctionalInterface
public interface IDGenerator<T> {

    T generate();

    /**
     * 使用UUID生成id
     */
    IDGenerator<String> UUID = () ->java.util.UUID.randomUUID().toString();
    /**
     * 8位随机字符
     */
    IDGenerator<String> RANDOM = RandomUtil ::randomChar;
    /**
     * mde(uuid()+random())
     */
    IDGenerator<String> MD5 = () -> {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(UUID.generate().concat(RandomUtil.randomChar()).getBytes());
            return new BigInteger(1,digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            throw  new RuntimeException(e);
        }

    };
    /**
     * 雪花算法生成id
     */
    IDGenerator<Long> SNOW_FLAKE = SnowflakeIdGenerator.getInstance() :: nextId;
    /**
     * 雪花算法id转string
     */
    IDGenerator<String> SNOW_FLAKE_STRING = () -> String.valueOf(SNOW_FLAKE.generate());
    /**
     * 雪花算法id 16进制
     */
    IDGenerator<String> SNOW_FLAKE_HEX = () -> Long.toHexString(SNOW_FLAKE.generate());
}

